﻿namespace LogViewApp
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System;
    using System.Xml.Linq;
    using System.Threading;
    using System.Windows.Threading;
    using LogViewApp.ServiceReference1;
    using System.Diagnostics;
    using System.Collections.Generic;
    using System.ServiceModel;

    public partial class MainPage : UserControl
    {
        public MainPage(IDictionary<string, string> initParams)
        {
            InitializeComponent();
            App app = Application.Current as App;
            app.initParams = initParams;
            //LoadConfiguration(initParams);
            
        }


        /// <summary>
        ///     After the Frame navigates, ensure the <see cref="HyperlinkButton"/> representing the current page is selected
        /// </summary>
        private void ContentFrame_Navigated(object sender, NavigationEventArgs e)
        {
            foreach (UIElement child in LinksStackPanel.Children)
            {
                HyperlinkButton hb = child as HyperlinkButton;
                if (hb != null && hb.NavigateUri != null)
                {
                    if (hb.NavigateUri.ToString().Equals(e.Uri.ToString()))
                    {
                        VisualStateManager.GoToState(hb, "ActiveLink", true);
                    }
                    else
                    {
                        VisualStateManager.GoToState(hb, "InactiveLink", true);
                    }
                }
            }
        }

        /// <summary>
        ///     If an error occurs during navigation, show an error window
        /// </summary>
        private void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            e.Handled = true;
            ErrorWindow.CreateNew(e.Exception);
        }


        public void AddLogViewtoFramework(string xmlFileName, Guid guid)
        {
            string title = ConvertXmlFileNameToShortTitle(xmlFileName);
            var newLogViewButton = new HyperlinkButton();
            /*
             <HyperlinkButton x:Name="Link1" Style="{StaticResource LinkStyle}" 
                                     NavigateUri="/Home" TargetName="ContentFrame" Content="{Binding Path=ApplicationStrings.HomePageTitle, Source={StaticResource ResourceWrapper}}"/>
             */
            newLogViewButton.Name = "LogView_" + title;
            newLogViewButton.Style = (Style)Application.Current.Resources["LinkStyle"];
            newLogViewButton.NavigateUri = new System.Uri(string.Format("/logView?Log={0}&Guid={1}", xmlFileName, guid), System.UriKind.Relative);
            newLogViewButton.TargetName = "ContentFrame";
            newLogViewButton.Content = title;

            var newdivider = new Rectangle();
            newdivider.Style = (Style)Application.Current.Resources["DividerStyle"];

            //LinksStackPanel.Children.Add(newdivider);
            LinksStackPanel.Children.Insert(2, newdivider);
            LinksStackPanel.Children.Insert(2, newLogViewButton);
        }

        internal static string ConvertXmlFileNameToShortTitle(string xmlFileName)
        {
            //xmlFileName sample "InstLog__201046_11'25'51"
            //remove the ".xml"
            string temp = xmlFileName;
            int indexOfDot =  temp.LastIndexOf('.');
            if (indexOfDot != -1)
            {
                temp = temp.Substring(0, indexOfDot);
            }

            int indexOfUnderScore = temp.IndexOf("__");
            if (indexOfUnderScore != -1)
            {
                temp = temp.Substring(indexOfUnderScore + 2);
            }
            return temp;

        }

        private System.Collections.ObjectModel.ObservableCollection<ViewModel.HomeViewModel.logFileEntry> _fileList;

        internal void SetLogFileList(System.Collections.ObjectModel.ObservableCollection<ViewModel.HomeViewModel.logFileEntry> fileList)
        {
            _fileList = fileList;
        }

        internal System.Collections.ObjectModel.ObservableCollection<ViewModel.HomeViewModel.logFileEntry> GetLogFileList()
        {
            return _fileList;
        }

        internal XElement GetLogFileXElementByGuid(Guid guid)
        {
            if (_fileList == null)
                return null;
            foreach (var file in _fileList)
            {
                if (file.guid.Equals(guid))
                {
                    return file.xLogFile;
                }
            }
            return null;
        }

        internal void NagivateToLogView(string xmlFileName, Guid guid)
        {
            ContentFrame.Navigate(new Uri(string.Format("/logView?Log={0}&Guid={1}", xmlFileName, guid), System.UriKind.Relative));
        }

 

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            SetTimer();
        }

        DispatcherTimer timer;
        
        private void SetTimer()
        {
            if (timer == null)
            {
                timer = new DispatcherTimer();
                timer.Tick += (s, e) =>
                    {
                        var client = new PingServiceClient(new BasicHttpBinding(), new EndpointAddress(new Uri(App.Current.Host.Source, "../../PingService.svc")));

                        //client.GetServerTimeCompleted += (se, arg) =>
                        //{
                        //    if (arg.Error == null)
                        //    {
                        //        ServerTime.Text = arg.Result.ToLongTimeString();
                        //    }
                        //    else
                        //    {
                        //        timer.Stop();
                        //        MessageBox.Show(arg.Error.Message);
                        //    }
                        //};
                        //client.GetServerTimeAsync();

                        client.GetStatusUpdateCompleted += (se, arg) =>
                            {
                                if (arg.Error == null)
                                {
                                    string xmlString = arg.Result;
                                    XElement xResult = XElement.Parse(xmlString);
                                    XElement xTime = xResult.Element("Time");
                                    if (xTime != null)
                                    {
                                        ServerTime.Text = xTime.Value;
                                    }
                                    else
                                    {
                                        ServerTime.Text = "error";
                                    }
                                }
                                else
                                {
                                    timer.Stop();
                                    MessageBox.Show(arg.Error.Message);
                                }
                            };
                        client.GetStatusUpdateAsync();

                    };
                timer.Interval = new TimeSpan(0, 0, 1);
                timer.Start();
            }
        }
    }
}